package com.fishingwithme.android.ui.screens.map.handlers

import com.fishingwithme.android.R

/**
 * 绘制钓点导航线处理器
 */
class DrawSpotNavigationLineEventHandler : BaseHandler() {
    override val key: String = "drawSpotNavLine"
    override val icon: Int = R.mipmap.nav_line // 使用"timeline"图标表示绘制路线

    // Store navigation points in the context instead of local variables
    private val navigationPoints = mutableListOf<com.tencent.tencentmap.mapsdk.maps.model.LatLng>()
    private var polyline: com.tencent.tencentmap.mapsdk.maps.model.Polyline? = null
    private val parkingSpotMarkers =
        mutableListOf<com.tencent.tencentmap.mapsdk.maps.model.Marker>()

    override fun doAction() {
        // 激活绘制导航线模式
        super.doAction()

        // 设置点选择回调 when the handler becomes active
        this.setOnPointSelectedCallback { latitude, longitude ->
            try {
                // 添加新的点到路线中
                val latLng = com.tencent.tencentmap.mapsdk.maps.model.LatLng(latitude, longitude)
                navigationPoints.add(latLng)

                // 添加标记
                val markerOptions = com.tencent.tencentmap.mapsdk.maps.model.MarkerOptions(latLng)
                    .title("路径点 ${navigationPoints.size}")
                    .snippet("导航路线点")
                    .infoWindowEnable(true)

                val marker = map?.addMarker(markerOptions)
                marker?.showInfoWindow()
                marker?.let {
                    parkingSpotMarkers.add(it)
                    addMarkerToMap(it) // Add to context for management
                }

                redrawPolyline()
                updateNavigationPointsInData()
            } catch (e: Exception) {
                android.util.Log.w("DrawSpotNavLine", "Error handling point selection", e)
            }
        }
        clearPreviousRoute()
    }

    /**
     * Clear previous route using context management
     */
    private fun clearPreviousRoute() {
        try {
            navigationPoints.clear()

            // Remove all parking spot markers using context management
            parkingSpotMarkers.forEach { marker ->
                removeMarkerFromMap(marker)
            }
            parkingSpotMarkers.clear()

            // Remove polyline using context management
            polyline?.let {
                removePolylineFromMap(it)
            }
            polyline = null
        } catch (e: Exception) {
            android.util.Log.w("DrawSpotNavLine", "Error clearing previous route", e)
        }
    }

    /**
     * 重新绘制路线
     */
    private fun redrawPolyline() {
        try {
            // 移除旧的路线 using context management
            polyline?.let {
                removePolylineFromMap(it)
            }

            // 绘制新的路线
            if (navigationPoints.size >= 2) {
                val polylineOptions = com.tencent.tencentmap.mapsdk.maps.model.PolylineOptions()
                    .latLngs(navigationPoints)
                    .color(0xff00ff00.toInt()) // 绿色
                    .width(10f)

                polyline = map?.addPolyline(polylineOptions)
                polyline?.let {
                    addPolylineToMap(it) // Add to context for management
                }
            }
        } catch (e: Exception) {
            android.util.Log.w("DrawSpotNavLine", "Error redrawing polyline", e)
        }
    }

    /**
     * 更新共享数据中的导航点列表
     */
    private fun updateNavigationPointsInData() {
        // 将导航点转换为可序列化的格式
        val pointsList = navigationPoints.map { latLng ->
            mapOf(
                "latitude" to latLng.latitude,
                "longitude" to latLng.longitude
            )
        }

        // 存储到共享的data中
        data?.set("navigationPoints", pointsList)
    }

    override fun reset() {
        super.reset()
        clearPreviousRoute()
        // 清除共享数据中的导航点
        data?.remove("navigationPoints")
    }
}